<script setup lang="ts">
import { computed, ref } from 'vue';

import {
  BookOutlined,
  CrownOutlined,
  EnvironmentOutlined,
  FilePdfOutlined,
  FileTextOutlined,
  PlusOutlined,
  ShareAltOutlined,
  ToolOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { marked } from 'marked';

interface Knowledge {
  id: string;
  title: string;
  description: string;
  category: string;
  content: string;
  author: string;
  createTime: string;
}

const selectedCategory = ref(['all']);
const viewModalVisible = ref(false);
const showEditModal = ref(false);
const selectedKnowledge = ref<Knowledge | null>(null);
const editingKnowledge = ref({
  title: '',
  category: 'rules',
  description: '',
  content: '',
});

const knowledgeList = ref<Knowledge[]>([
  {
    id: 'k-1',
    title: '朱氏家训十则',
    description: '太祖洪武皇帝亲定，子孙世代遵循',
    category: 'rules',
    content: `# 朱氏家训十则

## 第一则：忠孝为本
子孙当以忠孝为本，报国恩，事父母，不得有违。

## 第二则：勤俭持家
虽贵为皇族，亦当勤俭持家，不得奢靡浪费。

## 第三则：读书明理
子孙当勤读诗书，明理知礼，不得荒废学业。

## 第四则：兄友弟恭
兄弟当和睦相处，互相扶持，不得争斗。

## 第五则：敬老爱幼
尊敬长辈，爱护幼小，维护家族和谐。

（其余五则...）`,
    author: '朱元璋',
    createTime: '1398-05-10T10:00:00Z',
  },
  {
    id: 'k-2',
    title: '朱氏迁徙路线图',
    description: '记录家族从濠州到南京的迁徙历程',
    category: 'migration',
    content: `# 朱氏迁徙路线

## 起源地：濠州钟离（今安徽凤阳）
- 时间：元朝至正年间
- 人物：朱元璋出生地

## 第一站：皇觉寺
- 时间：至正四年（1344）
- 事件：朱元璋出家为僧

## 第二站：滁州
- 时间：至正十二年（1352）
- 事件：投奔郭子兴

## 第三站：南京（应天府）
- 时间：至正十六年（1356）
- 事件：攻克南京，建立根据地

## 建都：南京
- 时间：洪武元年（1368）
- 事件：正式建都南京

（详细地图待补充...）`,
    author: '朱橚',
    createTime: '1420-03-15T10:00:00Z',
  },
  {
    id: 'k-3',
    title: '《救荒本草》精要',
    description: '周定王朱橚编撰，记录414种救荒植物',
    category: 'skills',
    content: `# 救荒本草精要

## 简介
《救荒本草》由周定王朱橚主持编撰，记录可食用野生植物414种，用于荒年救灾。

## 主要植物

### 一、榆树
- 特征：叶可食，果实称榆钱
- 食用方法：嫩叶洗净蒸食，榆钱磨粉作饼

### 二、槐树
- 特征：花可食，豆荚亦可食
- 食用方法：槐花蒸食，豆荚煮熟去壳

### 三、野菜类
- 苋菜、马齿苋、荠菜等
- 均可洗净煮食

（详细内容414种...）`,
    author: '朱橚',
    createTime: '1406-08-20T10:00:00Z',
  },
]);

const filteredKnowledge = computed(() => {
  const category = selectedCategory.value[0];
  if (category === 'all') {
    return knowledgeList.value;
  }
  return knowledgeList.value.filter((k) => k.category === category);
});

function getCategoryIcon(category: string) {
  const icons: Record<string, string> = {
    rules: '训',
    migration: '路',
    skills: '技',
    culture: '文',
  };
  return icons[category] || '知';
}

function getCategoryText(category: string) {
  const texts: Record<string, string> = {
    rules: '家规祖训',
    migration: '迁徙路线',
    skills: '行业技艺',
    culture: '家族文化',
  };
  return texts[category] || category;
}

function formatTime(time: string) {
  return dayjs(time).format('YYYY年MM月DD日');
}

function renderMarkdown(text: string) {
  return marked(text);
}

function viewKnowledge(knowledge: Knowledge) {
  selectedKnowledge.value = knowledge;
  viewModalVisible.value = true;
}

function editKnowledge(knowledge: Knowledge) {
  editingKnowledge.value = { ...knowledge };
  showEditModal.value = true;
}

function saveKnowledge() {
  message.success('知识保存成功！（Mock模式）');
  showEditModal.value = false;
}

function exportPDF(knowledge: Knowledge) {
  message.success(`正在导出《${knowledge.title}》为PDF...（Mock模式）`);
}

function shareKnowledge(knowledge: Knowledge) {
  message.success('分享链接已复制到剪贴板！（Mock模式）');
}
</script>

<template>
  <div class="knowledge-base">
    <a-card>
      <template #title>
        <div class="page-header">
          <span>📚 家族知识库</span>
          <a-button type="primary" @click="showEditModal = true">
            <PlusOutlined /> 添加知识
          </a-button>
        </div>
      </template>

      <a-row :gutter="16">
        <a-col :span="6">
          <a-menu v-model:selected-keys="selectedCategory" mode="inline">
            <a-menu-item key="all"> <BookOutlined /> 全部 </a-menu-item>
            <a-menu-item key="rules">
              <FileTextOutlined /> 家规祖训
            </a-menu-item>
            <a-menu-item key="migration">
              <EnvironmentOutlined /> 迁徙路线
            </a-menu-item>
            <a-menu-item key="skills"> <ToolOutlined /> 行业技艺 </a-menu-item>
            <a-menu-item key="culture">
              <CrownOutlined /> 家族文化
            </a-menu-item>
          </a-menu>
        </a-col>

        <a-col :span="18">
          <a-list
            :data-source="filteredKnowledge"
            :pagination="{ pageSize: 5 }"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <a @click="viewKnowledge(item)">查看</a>
                  <a @click="editKnowledge(item)">编辑</a>
                  <a @click="exportPDF(item)">导出PDF</a>
                </template>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar style="background-color: #1890ff">
                      {{ getCategoryIcon(item.category) }}
                    </a-avatar>
                  </template>
                  <template #title>
                    <a-space>
                      <span>{{ item.title }}</span>
                      <a-tag>{{ getCategoryText(item.category) }}</a-tag>
                    </a-space>
                  </template>
                  <template #description>
                    {{ item.description }}
                  </template>
                </a-list-item-meta>
                <div class="knowledge-meta">
                  <div>创建：{{ formatTime(item.createTime) }}</div>
                  <div>作者：{{ item.author }}</div>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </a-col>
      </a-row>
    </a-card>

    <!-- 查看知识Modal -->
    <a-modal
      v-model:open="viewModalVisible"
      :title="selectedKnowledge?.title"
      width="900px"
    >
      <div v-if="selectedKnowledge" class="knowledge-content">
        <div v-html="renderMarkdown(selectedKnowledge.content)"></div>

        <a-divider />

        <a-space>
          <a-button @click="exportPDF(selectedKnowledge)">
            <FilePdfOutlined /> 导出PDF
          </a-button>
          <a-button @click="shareKnowledge(selectedKnowledge)">
            <ShareAltOutlined /> 分享
          </a-button>
        </a-space>
      </div>
    </a-modal>

    <!-- 编辑知识Modal -->
    <a-modal
      v-model:open="showEditModal"
      title="编辑知识"
      width="900px"
      @ok="saveKnowledge"
    >
      <a-form :model="editingKnowledge" layout="vertical">
        <a-form-item label="标题">
          <a-input v-model:value="editingKnowledge.title" />
        </a-form-item>
        <a-form-item label="分类">
          <a-select v-model:value="editingKnowledge.category">
            <a-select-option value="rules">家规祖训</a-select-option>
            <a-select-option value="migration">迁徙路线</a-select-option>
            <a-select-option value="skills">行业技艺</a-select-option>
            <a-select-option value="culture">家族文化</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="描述">
          <a-input v-model:value="editingKnowledge.description" />
        </a-form-item>
        <a-form-item label="内容（支持Markdown）">
          <a-textarea
            v-model:value="editingKnowledge.content"
            :rows="15"
            placeholder="使用Markdown格式编写..."
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
